//
//  AMapHelper.m
//  EasyCar
//
//  Created by nsm on 2017/4/27.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "AMapHelper.h"

@interface AMapHelper () <AMapLocationManagerDelegate>
@end

@implementation AMapHelper
+ (void)registerApp:(NSString *)apiKey {
    [AMapServices sharedServices].apiKey = apiKey;
}

+ (instancetype)sharedInstance {
    static AMapHelper *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [AMapHelper new];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _selectedCity = [self defaultCity];
    }
    return self;
}

//- (void)setSelectedCity:(CityModel *)selectedCity {
//    if ([_selectedCity.cid isEqual:selectedCity.cid]) {
//        return;
//    }
//    _selectedCity = selectedCity;
//    [_noteCenter postNotificationOnMainThreadWithName:kLocationDidChangeNotification
//                                               object:selectedCity];
//}

- (CityModel *)defaultCity {
    return [CityModel modelWithJSON:@{@"id": @"90",
                                      @"citycode": @"0710",
                                      @"cityname": @"襄阳市",
                                      @"initials": @"X"}];
}

- (AMapLocationManager *)locationManager {
    static AMapLocationManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AMapLocationManager new];
        manager.delegate = self;
        manager.locatingWithReGeocode = YES;
        // manager.allowsBackgroundLocationUpdates = NO;
    });
    return manager;
}

#pragma mark - setter/getter

#pragma mark - AMapLocationManagerDelegate
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
//    _userCoordinate = location.coordinate;
//    _appCache.userLocation = location;
//    // 同步保存定位数据
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        _appCache.userLocation = location;
//    });
//    
//    if (!reGeocode) return;
//
//    CityModel *city = [CityModel new];
//    city.code = reGeocode.citycode;
//    city.name = reGeocode.city;
//    self.city = city;
//    
//    // 同步保存定位城市
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        _appCache.userCity = city;
//    });
}

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    if (self.locationDidFailWithError)
        self.locationDidFailWithError(error);
}

@end
